import React from 'react'
import {inject, observer} from 'mobx-react';
import {
  Icon, Tools, Flex,Checkbox,
  ListView, SwipeAction,ActivityIndicator,List,PullToRefresh
} from 'weaver-mobile';
import {Upload,Share} from 'weaver-mobile-page';
import {withRouter, Route} from 'react-router-dom';
import {toJS} from 'mobx';
import {Browser} from 'weaver-mobile-page';
import SearchHistory from './SearchHistory';
import OpenAttach from '../fileView/openattach';
import QueueAnim from 'rc-queue-anim';
import FloatButton from '../../util/FloatButton';
import MyShareObjPage from '../netdisk/MyShareObjPage'
import {GetUrlParam} from '../../util/Utils'
import DocConstant from '../../util'

const getLabel = Tools.getLabel;

@withRouter
@inject('netdiskStore')
@observer
class CategoryMode extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      uploadids:[],
      uploaddatas:[],
    }
  }
  componentDidMount() {
    const {store, path,netdiskStore} = this.props;
    netdiskStore.isOpenFile = false;
    let url = this.props.location.search;
    let resource = GetUrlParam(url,'resource');
    let type = GetUrlParam(url,'type');
    let fid = GetUrlParam(url,'fid');
    let pathname = this.props.location.pathname;
    let folderList = pathname.split("/");
    let folderid = folderList[folderList.length-1];
    netdiskStore.searchFolderid = folderid;
    store.currentPageNum = 1;
    if(resource === 'em' && type === 'folder'){
      if (DocConstant.isApp()) {
        new Promise((resolve, reject) => {
          window.em.getTitle({'success':function (argument) {
            resolve(argument);
          },'fail':function (argument) {
            reject(argument);
          }});
        }).then((res) => {
          this.prevTitle = res && res.result;
          if(!res || !res.result){
            window.em.changeTitle({
              title: getLabel(129207,'我的云盘')
            });
          }
        }).catch(() => {
          this.prevTitle = '';
        });
      } else {
        this.prevTitle = window.document.title;
        window.document.title = getLabel(129207,'我的云盘');
      }
    }
    store.init({resource,type,fid});
    store.initBrowser(path);
  }
  goBack = () => {
    const {store,netdiskStore} = this.props;
    let categoryInfo = toJS(store.categoryInfo)
    let parentCategoryInfo = (store.parent && store.parent.categoryInfo) ? toJS(store.parent.categoryInfo) : null;
    if(parentCategoryInfo){
      netdiskStore.searchFolderid = parentCategoryInfo.id;
    }else{
      netdiskStore.searchFolderid = "";
    }
    if (categoryInfo) {
      categoryInfo.id && this.props.history.go(-1);
      if(store.parent.categoryInfo){
        store.parent.setChild(null);
      }
    }
  }
  //附件打开组件卸载时执行
  attachUnMount = () =>{
    const {store,netdiskStore} = this.props;
    store.attachTitle = '';
    netdiskStore.isOpenFile = false;
  }
  render() {
    const {store, path, netdiskStore, history} = this.props,
      {browser,categoryBrowser, loading, uploadList, categoryOper,shareStore,shareData} = store,
      {multiOper,selectedTab,} = netdiskStore;
    const searchBarName = selectedTab === 'disk' ? getLabel(129207, '我的云盘') : (selectedTab === 'myShare' ? getLabel(33310, '我的分享') : getLabel(129146, '同事的分享'))
    let categoryInfo = toJS(store.categoryInfo), chooseIds = toJS(store.chooseIds),
      isChooseAll = chooseIds.length < store.datasource.getRowCount();
    const barClsPre = 'netdisk-category-bar';
    const itemClsPre = 'netdisk-list-row';
    let categoryOperParems = {...categoryOper.dataParams,noAllDirName:'1',iscreate:"1"}
    if (loading) {
      return (
        <div className="wea-doc-whitebg">
          <div className="wea-doc-error">
            <ActivityIndicator size="large"/> 
          </div>
        </div>
      );
    }
    return (
      <div className="netdisk-list-scroll-div">
        <Route
          key="netdisk-file"
          path={`${path}/file/attach/:fileid`}
          render={() => {
            return (
              <QueueAnim>
                <div className="wm-route-layout" key="news-doc-div">
                  <OpenAttach 
                    dataParams={{title:store.attachTitle,prevTitle:getLabel(129207,'我的云盘'),resource:"netdisk"}}
                    didmount={() => netdiskStore.isOpenFile = true}
                    unmount={() => this.attachUnMount()}
                   />
                </div>
              </QueueAnim>
            );
          }}
        />
        <Route
          key="netdisk-myshare-userlist"
          path={`${path}/myshare/userlist`}
          render={() => {
            return (
              <QueueAnim>
                <div className="wm-route-layout" key="news-myshare-div">
                  <MyShareObjPage store={store}/>
                </div>
              </QueueAnim>
            );
          }}
        />
        <SearchHistory store={store}/>
        <div style={{display: 'none'}}>
          <Browser
            label={getLabel(32452, '目录')}
            store={browser}
            hasAdvanceSerach
            type={'doccategory'}
            dataParams={{sharetype: selectedTab,noAllDirName:'1',iscreate:"1"}}
            onOk={store.chooseSystemCategory}
          />
        </div>
        <div style={{display: 'none'}}>
          <Browser
            label={getLabel(32452, '目录')}
            store={categoryBrowser}
            hasAdvanceSerach
            type={'networkdisk'}
            dataParams={categoryOperParems}
            onOk={store.chooseCategory}
          />
          {shareStore && <Route
            key="netdisk-share"
            path={shareStore.path}
            render={() => {
              return (
                <Share shareParams={{url: '/api/networkdisk/clouddisk/share', ...store.shareParams}} store={shareStore} msgList={shareData}/>
              );
            }}
          />}
        </div>
        <Flex className={barClsPre}>
          <div className={`${barClsPre}-topIcon`} onClick={this.goBack}><Icon type="return-01" size="xs"/></div>
          <div className={`${barClsPre}-treeIcon`} onClick={() => store.goCategoryBrowser((id, name) => {
              if (!categoryInfo || id !== categoryInfo.id) {
                window.setTimeout(() => {
                  store.setChild({id: id, name: name}).then(() => {
                    this.props.history.push(path + "/" + id);
                  });
                }, 0);
              }
            }, history, null, {sharetype: selectedTab})}>
            <Icon type="branch" size="xs"/>
            <span
              className={`${barClsPre}-treeLabel-div`}>{categoryInfo && categoryInfo.name ? categoryInfo.name : searchBarName}</span>
          </div>
        </Flex>
        {multiOper &&
          <div className="netdisk-multi-header">
            <a onClick={store.cancelMultiOper}>{getLabel(31129, '取消')}</a>
            <span>{getLabel(31503, '已选择') + chooseIds.length + getLabel(18256, '条')}</span>
            <span className="netdisk-multi-choose-all"
                  onClick={isChooseAll ? store.chooseAll : store.chooseNone}>
              {isChooseAll ? getLabel(556, '全选') : getLabel(311, '清除')}
              </span>
          </div>
        }
        <ListView
          ref={el => this.lv = el}
          dataSource={store.datasource}
          renderRow={(rowData, sectionID, rowID) => {
            let checked = multiOper && chooseIds.some((id) => id === `${rowData.type}-${rowData.id}`);
            let content;
            if (rowData.type === 'file') {
              content = (
                <List.Item
                  onClick={() => this.touchRow(rowData,multiOper)}
                >
                  <div className={`${itemClsPre} ${itemClsPre}-file`}>
                    {multiOper &&
                    <Checkbox
                      key={`${rowData.type}-${rowData.id}`}
                      checked={checked}/>}
                    {
                      rowData.icon.iconUrl ?
                        <img src={rowData.icon.iconUrl} alt="" className={`${itemClsPre}-img`}/>
                        :
                        <Icon type={`${rowData.icon.iconType}`} size="lg" className={`${itemClsPre}-img`} color={`${rowData.icon.iconColor}`}/>
                    }
                    <div className={`${itemClsPre}-content`}>
                      <div className={`${itemClsPre}-title`}>
                        {rowData.name}
                      </div>
                      <div className={`${itemClsPre}-sub`}>
                                    <span>
                                    {rowData.datetime}
                                    </span>
                        <span className={`${itemClsPre}-sub-right`}>
                                    {rowData.size}
                                    </span>
                      </div>
                    </div>
                  </div>
                </List.Item>
              );
            } else {
              content = (
                <List.Item onClick={() => this.touchRow(rowData, multiOper)}>
                  <div className={`${itemClsPre} ${itemClsPre}-folder`}>
                    {multiOper &&
                    <Checkbox
                      key={`${rowData.type}-${rowData.id}`}
                      checked={checked}/>}
                    <Icon type="folder" alt="" className={`${itemClsPre}-img`}
                          style={rowData.img ? {display: 'none'} : {display: 'inline-block'}}/>
                    <div className={`${itemClsPre}-content`}>
                      <div className={`${itemClsPre}-title ${rowData.type === 'folder' ? 'pt-md' : ''}`}>
                        {rowData.name}
                      </div>
                    </div>
                  </div>
                </List.Item>
              );
            }
            if (multiOper) {
              return content;
            } else {
              return (
                <SwipeAction
                  autoClose
                  right={store.getRightButton(path, rowData, history)}
                >
                  {content}
                </SwipeAction>
              );
            }
          }}
          className='wea-netdisk-list'
          style={store.datasource.getRowCount() > 0 ? {display: 'block'} : {display: 'none'}}
          pageSize={20}
          initialListSize={20}
          scrollRenderAheadDistance={500}
          onEndReachedThreshold={10}
          onEndReached={store.getNextPageList}
          pullToRefresh = {
            <PullToRefresh
              refreshing={store.netdiskListRefreshing}
              onRefresh={()=>store.getonRefresh()}
            />
          }
        />
        {store.datasource.getRowCount() === 0 &&
        <div className="wea-doc-error">
          <Icon type="no-data" size="lg"/>
          <div>{getLabel(83553, '暂无数据')}</div>
        </div>
        }
        {selectedTab === 'disk' && !multiOper &&
        <FloatButton
          className="wea-netdisk-upload"
          activeClassName="wea-netdisk-upload-active"
          lowestBottom={55}
          highestTop={86}
          defaultBottom={25}>
          <Upload
            uploadUrl="/api/doc/upload/uploadFile"
            datas={toJS(uploadList)} 
            limitType={netdiskStore.diskLimitType}
            onChange={(ids,datas)=>{
              let uploadids = this.state.uploadids;
              let uploaddatas = this.state.uploaddatas;
              uploadids.push(ids[0]);
              uploaddatas.push(datas[0]);
              this.setState({
                uploadids: uploadids,
                uploaddatas: uploaddatas,
              });
            }} 
            showFileList={false}
            onUploading={status=>{
              if(status === "uploaded"){
                store.upload(this.state.uploadids,this.state.uploaddatas);
                this.setState({
                  uploadids: [],
                  uploaddatas: [],
                });
              }
            }}
            >
            <div className="wea-netdisk-upload-content">
              <div>
                <Icon type="upload-1"/>
              </div>
              <div>
                <span>{getLabel(75, '上传')}</span>
              </div>
            </div>
          </Upload>
        </FloatButton>}
      </div>
    )
  }
  
  touchRow = (rowData, multiOper) => {
    const {store, path,netdiskStore} = this.props;
    if (multiOper) {
      store.choose(rowData);
    } else {
      if (rowData.type === 'file') {
        netdiskStore.isOpenFile = true;
        store.attachTitle = rowData.name;
        this.props.history.push(path+"/file/attach/" + rowData.id);
      } else if (rowData.type === 'folder') {
        store.setChild(rowData).then(() => {
          this.props.history.push(path + "/" + rowData.id);
        });
      }
    }
  }
}

export default CategoryMode